package com.zlp.netty.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @author: zhulaiping
 * @time: 2022/8/24 14:21
 */
@Slf4j
public class NIOServerDemo4_Writer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        serverSocketChannel.bind(new InetSocketAddress(8080));
        //notWrite(selector);
        haveWrite(selector);
    }

    private static void haveWrite(Selector selector) throws IOException {
        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();;
                log.debug("key:{}",key);
                if(key.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);

                    StringBuilder builder = new StringBuilder();
                    for (int i=0;i<30000000;i++){
                        builder.append("a");
                    }
                    ByteBuffer buffer = Charset.defaultCharset().encode(builder.toString());
                    int write = socketChannel.write(buffer);
                    System.out.println(write);
                    if (buffer.hasRemaining()){
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector,SelectionKey.OP_WRITE,buffer);
                    }
                }else if(key.isWritable()){
                    ByteBuffer buffer = (ByteBuffer)key.attachment();
                    SocketChannel channel = (SocketChannel) key.channel();
                    int write = channel.write(buffer);
                    System.out.println(write);
                    if(!buffer.hasRemaining()){
                        key.attach(null);
                        //取消可写事件
                        key.interestOps(key.interestOps()-SelectionKey.OP_WRITE);
                    }
                }
            }
        }
    }

    /**
     * 没有使用可写事件实现时，cpu会一直询问，造成空转
     * @param selector
     * @throws IOException
     */
    private static void notWrite(Selector selector) throws IOException {
        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();;
                log.debug("key:{}",key);
                if(key.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);

                    StringBuilder builder = new StringBuilder();
                    for (int i=0;i<30000000;i++){
                        builder.append("a");
                    }
                    ByteBuffer buffer = Charset.defaultCharset().encode(builder.toString());
                    while (buffer.hasRemaining()){
                        int write = socketChannel.write(buffer);
                        System.out.println(write);
                    }
                }
            }
        }
    }
}
